package com.wmlive.hhvideo.heihei.personal;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.util.SparseArrayCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wmlive.hhvideo.application.DCApplication;
import com.wmlive.hhvideo.common.GlobalParams;
import com.wmlive.hhvideo.common.base.DcBaseFragment;
import com.wmlive.hhvideo.common.navigator.Navigator;
import com.wmlive.hhvideo.heihei.beans.login.MobileLoginResponse;
import com.wmlive.hhvideo.heihei.beans.login.UserInfo;
import com.wmlive.hhvideo.heihei.beans.main.ShareInfo;
import com.wmlive.hhvideo.heihei.beans.personal.UserHomeData;
import com.wmlive.hhvideo.heihei.beans.personal.UserHomeRelation;
import com.wmlive.hhvideo.heihei.channel.ShareSdkUtils;
import com.wmlive.hhvideo.heihei.db.manager.IMMessageDefaultDBManager;
import com.wmlive.hhvideo.heihei.db.manager.IMMessageUserDBManager;
import com.wmlive.hhvideo.heihei.login.AccountUtil;
import com.wmlive.hhvideo.heihei.personal.activity.SettingActivity;
import com.wmlive.hhvideo.heihei.personal.adapter.MyFragmentPagerAdapter;
import com.wmlive.hhvideo.heihei.personal.fragment.PersonalLoveFragment;
import com.wmlive.hhvideo.heihei.personal.fragment.PersonalProductFragment;
import com.wmlive.hhvideo.heihei.personal.presenter.PersonalPresenter;
import com.wmlive.hhvideo.heihei.personal.view.IPersonalView;
import com.wmlive.hhvideo.utils.DensityUtils;
import com.wmlive.hhvideo.utils.DeviceUtils;
import com.wmlive.hhvideo.utils.MyClickListener;
import com.wmlive.hhvideo.utils.PopupWindowUtils;
import com.wmlive.hhvideo.utils.ToastUtil;
import com.wmlive.hhvideo.utils.imageloader.GlideLoader;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.wmlive.hhvideo.R;
import cn.wmlive.hhvideo.rxbuslib.RxBus2;
import cn.wmlive.hhvideo.rxbuslib.RxBusSubscribe;
import cn.wmlive.hhvideo.rxbuslib.ThreadMode;

/**
 * Created by XueFei on 2017/5/27.
 * <p>
 * 个人主页
 */

public class PersonalFragment extends DcBaseFragment implements IPersonalView, ViewPager.OnPageChangeListener, RecyclerScrollListener, PlatformActionListener {

    @BindView(R.id.iv_personal_header)
    ImageView ivPersonalHeader;
    @BindView(R.id.tv_personal_name)
    TextView tvPersonalName;
    @BindView(R.id.iv_personal_edit)
    ImageView ivPersonalEdit;
    @BindView(R.id.tv_personal_info)
    TextView tvPersonalInfo;
    @BindView(R.id.tv_personal_id)
    TextView tvPersonalId;
    @BindView(R.id.tv_personal_signature)
    TextView tvPersonalSignature;
    @BindView(R.id.ll_personal_focus)
    LinearLayout llPersonalFocus;
    @BindView(R.id.tv_personal_focus_count)
    TextView tvPersonalFocusCount;
    @BindView(R.id.ll_personal_fans)
    LinearLayout llPersonalFans;
    @BindView(R.id.tv_personal_fans_count)
    TextView tvPersonalFansCount;
    @BindView(R.id.ll_personal_stars)
    LinearLayout llPersonalStars;
    @BindView(R.id.tv_personal_stars_count)
    TextView tvPersonalStarsCount;
    @BindView(R.id.ll_personal_product)
    LinearLayout llPersonalProduct;
    @BindView(R.id.tv_personal_product_count)
    TextView tvPersonalProductCount;
    @BindView(R.id.ll_personal_love)
    LinearLayout llPersonalLove;
    @BindView(R.id.tv_personal_love_count)
    TextView tvPersonalLoveCount;
    @BindView(R.id.tv_peronsal_meeage)
    View tvPeronsalMeeage;
    @BindView(R.id.iv_peronsal_set)
    ImageView ivPeronsalSet;
    @BindView(R.id.iv_personal_add)
    ImageView ivPersonalAdd;
    @BindView(R.id.iv_peronsal_share)
    ImageView ivPeronsalShare;

    @BindView(R.id.vp_personal_fragments)
    ViewPager vpPersonalFragments;

    @BindView(R.id.top_1)
    LinearLayout top1;
    @BindView(R.id.rl_top)
    RelativeLayout rlTop;
    @BindView(R.id.ll_switch)
    LinearLayout llSwitch;
    //    @BindView(R.id.iv_personal_header_bg)
//    ImageView ivPersonalHeaderBg;
    @BindView(R.id.tv_user_name_bar)
    TextView tv_user_name_bar;

    private int rlTopHeight = 0;
    private RecyclerScrollListener mScrollListener;

    private int statusHeigth;

    private ArrayList<DcBaseFragment> mFraments;
    private PersonalProductFragment personalProductFragment;
    private PersonalLoveFragment personalLoveFragment;
    private MyFragmentPagerAdapter myFragmentPagerAdapter;

    private UserInfo userInfo;
    private ShareInfo shareInfo;//邀请好友的分享内容
    private ShareInfo shareHome;//个人页的分享内容
    private PopupWindow shareWindow;

    private PersonalPresenter personalPresenter;

    private int currentItemPosition = 0;
    private int currentDistance = 0;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_personal;
    }

    @Override
    public void onStart() {
        super.onStart();

        if (null != personalPresenter) {
            personalPresenter.setView(this);

            personalPresenter.setUserInfo();
        }
    }

    @Override
    protected void initData() {
        super.initData();
        statusHeigth = DeviceUtils.getStatusBarHeight(getActivity());
        RelativeLayout.LayoutParams l = (RelativeLayout.LayoutParams) top1.getLayoutParams();
        l.topMargin = statusHeigth;

        personalPresenter = new PersonalPresenter(this);
        addPresenter(personalPresenter);

        llPersonalProduct.setSelected(true);
        llPersonalLove.setSelected(false);

        tv_user_name_bar.setAlpha(0);

        int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        rlTop.measure(width, height);

        rlTopHeight = rlTop.getMeasuredHeight() - DeviceUtils.dip2px(getActivity(), 88 + 15);

        bindListener();

        mScrollListener = this;
        updateDateBell();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            /**
             * 解决 首页 滑动问题
             */
            if (currentItemPosition == 0) {
                vpPersonalFragments.setCurrentItem(1, false);
                currentItemPosition = 0;
            }
        } else {
            if (vpPersonalFragments.getCurrentItem() != currentItemPosition) {
                vpPersonalFragments.setCurrentItem(currentItemPosition, false);
            }

            /**
             * 因解决 首页 滑动问题出现的问题
             *
             * 解决了滑动到某个位置，切到首页，在切到个人页，保持不变
             */
            Scrolled(currentDistance, 0);

            if (null != personalPresenter) {
                personalPresenter.setView(this);

                personalPresenter.setUserInfo();
            }

            updateDateBell();
        }
    }

    @OnClick(R.id.iv_peronsal_meeage)
    public void onBellClick() {
        Navigator.getInstance().navigateToBell(getActivity());
    }

    private void bindListener() {
        ivPersonalHeader.setOnClickListener(this);
        ivPersonalEdit.setOnClickListener(this);

        llPersonalFocus.setOnClickListener(this);
        llPersonalFans.setOnClickListener(this);

        llPersonalProduct.setOnClickListener(this);
        llPersonalLove.setOnClickListener(this);

        ivPeronsalSet.setOnClickListener(this);
        ivPersonalAdd.setOnClickListener(this);
        ivPeronsalShare.setOnClickListener(this);
    }

    @Override
    public void setUserInfoSucceed(MobileLoginResponse account) {
        userInfo = account.getUserInfo();
        if (null != userInfo) {
            String cover_url = userInfo.getCover_url();
            if (!TextUtils.isEmpty(cover_url)) {
                GlideLoader.loadCircleImage(cover_url, ivPersonalHeader, R.drawable.icon_profile_bg_user_default);
//                GlideLoader.loadImage(userInfo.getCover_ori(), ivPersonalHeaderBg, R.drawable.icon_profile_bg_user_default);
            }
            tvPersonalName.setText(userInfo.getName());
            tv_user_name_bar.setText(userInfo.getName());
            ivPersonalEdit.setVisibility(View.VISIBLE);
            String location = userInfo.getRegion();
            if (TextUtils.isEmpty(location)) {
                location = getResString(R.string.user_location_fail);
            }
            String constellation = userInfo.getConstellation();
            if (TextUtils.isEmpty(constellation)) {
                constellation = getResString(R.string.user_default_constellation);
            }
            tvPersonalInfo.setText(location + "  ·  " + constellation);

            tvPersonalId.setText(getString(R.string.user_id, userInfo.getDc_num()));

            if (!TextUtils.isEmpty(userInfo.getDescription())) {
                tvPersonalSignature.setVisibility(View.VISIBLE);
                tvPersonalSignature.setText(userInfo.getDescription());
            } else {
                tvPersonalSignature.setVisibility(View.GONE);
            }

            initViewPage();

            personalPresenter.getPersonalInfo(userInfo.getId());
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        RxBus2.get().register(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        RxBus2.get().unRegister(this);
    }

    @RxBusSubscribe(code = GlobalParams.RXBusCode.IM_NOTIFICATION_NEW_MSG, threadMode = ThreadMode.MAIN)
    public void receiveBellUpdateEvent() {
        updateDateBell();
    }

    /**
     * 更新铃铛状态
     */
    private void updateDateBell() {

        if (AccountUtil.isLogin()) {
            IMMessageUserDBManager userDBManager = IMMessageUserDBManager.getInstance(DCApplication.getDCApp());
            if (userDBManager.getImUserEntryUnReadCount() > 0) {//有未读消息
                tvPeronsalMeeage.setVisibility(View.VISIBLE);
            } else {//无未读消息
                tvPeronsalMeeage.setVisibility(View.GONE);
            }
        } else {
            IMMessageDefaultDBManager defaultDBManager = IMMessageDefaultDBManager.getInstance(DCApplication.getDCApp());
            if (defaultDBManager.getImDefaultEntryUnReadCount() > 0) {
                tvPeronsalMeeage.setVisibility(View.VISIBLE);
            } else {//无未读消息
                tvPeronsalMeeage.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void setUserInfoFailure() {
    }

    private void initViewPage() {
        if (null != mFraments && mFraments.size() > 0) {
            if (null != personalProductFragment) {
                personalProductFragment.setUserId(userInfo.getId());
            }
            if (null != personalLoveFragment) {
                personalLoveFragment.setUserId(userInfo.getId());
            }
            if (null != personalProductFragment && llPersonalProduct.isSelected()) {
                personalProductFragment.onRefresh();
            }
            if (personalLoveFragment != null && llPersonalLove.isSelected()) {
                personalLoveFragment.onRefresh();
            }
            return;
        }
        mFraments = new ArrayList<>();

        Bundle bundle = new Bundle();
        bundle.putLong("user_id", userInfo.getId());
        bundle.putInt("headHeight", rlTopHeight);
        bundle.putBoolean("isShowPop", true);
        bundle.putBoolean(LAZY_MODE, false);

        personalProductFragment = PersonalProductFragment.newInstance();
        personalProductFragment.getmScrollListener(mScrollListener);
        personalProductFragment.setArguments(bundle);

        bundle = new Bundle();
        bundle.putSerializable("user_id", userInfo.getId());
        bundle.putInt("headHeight", rlTopHeight);
        bundle.putBoolean(LAZY_MODE, true);
        personalLoveFragment = PersonalLoveFragment.newInstance();
        personalLoveFragment.getmScrollListener(mScrollListener);
        personalLoveFragment.setArguments(bundle);

        mFraments.add(personalProductFragment);
        mFraments.add(personalLoveFragment);
        myFragmentPagerAdapter = new MyFragmentPagerAdapter(getChildFragmentManager(), mFraments);
        vpPersonalFragments.setAdapter(myFragmentPagerAdapter);
        vpPersonalFragments.setOffscreenPageLimit(2);
        vpPersonalFragments.setOnPageChangeListener(this);
    }

    @Override
    public void handlePersonalInfoSucceed(UserInfo userHomeEntry) {
        userInfo = userHomeEntry;
        String cover_url = userHomeEntry.getCover_url();
        if (!TextUtils.isEmpty(cover_url)) {
            GlideLoader.loadCircleImage(cover_url, ivPersonalHeader, R.drawable.icon_profile_bg_user_default);
        }
        tvPersonalName.setText(userHomeEntry.getName());
        tv_user_name_bar.setText(userHomeEntry.getName());
        String location = userInfo.getRegion();
        if (TextUtils.isEmpty(location)) {
            location = getResString(R.string.user_location_fail);
        }
        String constellation = userInfo.getConstellation();
        if (TextUtils.isEmpty(constellation)) {
            constellation = getResString(R.string.user_default_constellation);
        }
        tvPersonalInfo.setText(location + "  ·  " + constellation);
        String description = userHomeEntry.getDescription();
        if (!TextUtils.isEmpty(description)) {
            tvPersonalSignature.setVisibility(View.VISIBLE);
            tvPersonalSignature.setText(description);
        } else {
            tvPersonalSignature.setVisibility(View.GONE);
        }

        UserHomeRelation userHomeRelation = userHomeEntry.getRelation();
        if (null != userHomeRelation) {
            tvPersonalFocusCount.setText(String.valueOf(userHomeRelation.getFollow_count()));
            tvPersonalFansCount.setText(String.valueOf(userHomeRelation.getFans_count()));
        } else {
            tvPersonalFocusCount.setText("0");
            tvPersonalFansCount.setText("0");
        }

        UserHomeData userHomeData = userHomeEntry.getData();
        if (null != userHomeData) {
            tvPersonalStarsCount.setText(String.valueOf(userHomeData.getLike()));
        } else {
            tvPersonalStarsCount.setText("0");
        }

        tvPersonalProductCount.setText("作品(" + String.valueOf(userHomeData.getOpus_count()) + ")");
        tvPersonalLoveCount.setText("喜欢(" + String.valueOf(userHomeData.getLike_opus_count()) + ")");

        AccountUtil.updateUserInfo(userInfo);

        shareInfo = userHomeEntry.getShare_info();
        shareHome = userHomeEntry.getShare_home();
    }

    @Override
    public void handlePersonalInfoFailure(String error_msg) {
        ToastUtil.showToast(error_msg);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        currentItemPosition = position;
        int currentItem = vpPersonalFragments.getCurrentItem();
        if (positionOffsetPixels > 0) {
            SparseArrayCompat<RecyclerScrollListener> scrollTabHolders = myFragmentPagerAdapter.getScrollTabHolders();
            RecyclerScrollListener fragmentContent;
            if (position < currentItem) {
                fragmentContent = scrollTabHolders.valueAt(position);
            } else {
                fragmentContent = scrollTabHolders.valueAt(position + 1);
            }
            fragmentContent.adjustScroll((int) (rlTopHeight + rlTop.getTranslationY()), rlTopHeight);
        }
    }

    @Override
    public void onPageSelected(int position) {
        SparseArrayCompat<RecyclerScrollListener> scrollTabHolders = myFragmentPagerAdapter.getScrollTabHolders();

        if (scrollTabHolders == null || scrollTabHolders.size() != mFraments.size()) {
            return;
        }
        rlTop.setTranslationY(0);
        top1.setAlpha(1);
        rlTop.invalidate();

        if (position == 0) {
            llPersonalProduct.setSelected(true);
            llPersonalLove.setSelected(false);
        } else if (position == 1) {
            llPersonalProduct.setSelected(false);
            llPersonalLove.setSelected(true);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    protected void onSingleClick(View v) {
        switch (v.getId()) {
            case R.id.iv_personal_header:
            case R.id.iv_personal_edit:
                if (null != userInfo) {
                    Navigator.getInstance().navigateToUserInfo(getActivity(), userInfo);
                }
                break;
            case R.id.ll_personal_focus:
                if (null != userInfo) {
                    Navigator.getInstance().navigateToFocus(getActivity(), userInfo);
                }
                break;
            case R.id.ll_personal_fans:
                if (null != userInfo) {
                    Navigator.getInstance().navigateToFans(getActivity(), userInfo);
                }
                break;
            case R.id.ll_personal_product:
                llPersonalProduct.setSelected(true);
                llPersonalLove.setSelected(false);
                vpPersonalFragments.setCurrentItem(0);
                break;
            case R.id.ll_personal_love:
                llPersonalProduct.setSelected(false);
                llPersonalLove.setSelected(true);
                vpPersonalFragments.setCurrentItem(1);
                break;
            case R.id.iv_peronsal_set:
                Intent intent = new Intent(getActivity(), SettingActivity.class);
                getActivity().startActivity(intent);
                break;
            case R.id.iv_personal_add:
                Navigator.getInstance().navigateToAddFriend(getActivity(), shareInfo);
                break;
            case R.id.iv_peronsal_share:
                shareWindow = PopupWindowUtils.showNormal(getActivity(), vpPersonalFragments, shareClick);
                break;
            default:
                break;
        }
    }

    @Override
    public void Scrolled(int distance, int pagePosition) {
//        if (distance >= (top1.getHeight() + statusHeigth)) {
//            return;
//        }
        float maxDis = -rlTopHeight + DeviceUtils.dip2px(getActivity(), 15);
        float translationY = Math.max(-distance, maxDis);
        rlTop.setTranslationY(translationY);

        float percent = Math.abs(translationY) / (float) Math.abs(rlTopHeight);
        float falpha = 1 - percent;
        top1.setAlpha(falpha);

//        tv_user_name_bar.setTranslationY(-translationY / 3);
        int tvPersonalNameTop = DensityUtils.dip2px(getActivity(), 90);
        int tvPersonalNameHeight = tvPersonalName.getHeight();
        if (distance > tvPersonalNameTop) {
            float namePercent = Math.abs(translationY) / (float) Math.abs(rlTopHeight - tvPersonalNameHeight - tvPersonalNameTop);
            tv_user_name_bar.setAlpha(namePercent);
        } else {
            tv_user_name_bar.setAlpha(0);
        }
        currentDistance = distance;
    }

    @Override
    public void adjustScroll(int scrollHeight, int headerHeight) {

    }

    private MyClickListener shareClick = new MyClickListener() {
        @Override
        protected void onMyClick(View v) {
            switch (v.getId()) {
                case R.id.llWeChat:
                    loading();
                    ShareSdkUtils.getInstance().showWechatShare(getActivity(), shareHome, PersonalFragment.this);
                    break;
                case R.id.llCircle:
                    loading();
                    ShareSdkUtils.getInstance().showWechatMomentsShare(getActivity(), shareHome, PersonalFragment.this);
                    break;
                case R.id.llWeibo:
                    loading();
                    ShareSdkUtils.getInstance().showWeiboShare(getActivity(), shareHome, PersonalFragment.this);
                    break;
                case R.id.llQQ:
                    loading();
                    ShareSdkUtils.getInstance().showQQShare(getActivity(), shareHome, PersonalFragment.this);
                    break;
                case R.id.llCopy:
                    ClipboardManager cmb = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                    cmb.setPrimaryClip(ClipData.newPlainText(null, shareHome.getShare_url()));
                    showToast(R.string.copy_succeed);
                    break;
            }
            if (null != shareWindow && shareWindow.isShowing()) {
                shareWindow.dismiss();
            }
        }
    };

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        dismissLoad();
        ToastUtil.showToast(R.string.share_suc);
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        dismissLoad();
        ToastUtil.showToast(R.string.share_faid);
    }

    @Override
    public void onCancel(Platform platform, int i) {
        dismissLoad();
        ToastUtil.showToast(R.string.share_cancel);
    }
}
